<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20" class="my-3">
        <el-col :span="4" v-permission="['sys:user:delete']">
          <el-button @click="delAllSelection" :disabled="!multipleSelection.length" type="button"
            class="el-button handle-del  el-button--primary  ">
            <i class="el-icon-delete"></i><span>批量删除</span>
          </el-button>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" v-model="searchContent" clearable>
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4" v-permission="['sys:user:save']">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="centerDialogVisible = true">
              <i class="el-icon-plus"></i> <span>添加用户</span>
            </el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table border stripe :data="userList" ref="multipleTable" @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }" style="width: 100%">
        <el-table-column type="selection" show-overflow-tooltip></el-table-column>

        <el-table-column type="index" :index="indexSort" sortable align="center" label="#" width="50">
        </el-table-column>
        <el-table-column align="center" prop="username" label="用户名">
        </el-table-column>
        <el-table-column align="center" label="头像(查看大图)">
          <template #default="scope">
            <el-image class="table-td-headPortrait" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="phone" label="电话">
        </el-table-column>
        <el-table-column align="center" prop="email" label="邮箱">
        </el-table-column>
        <el-table-column align="center" prop="gender" label="性别">
        </el-table-column>
        <el-table-column align="center" label="角色">
          <template #default="{ row }">
            <div v-for="(item, index) in row.roles" :key="index">
              {{ item.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="250px" label="操作">
          <template slot-scope="scope">
            <el-tooltip v-permission="['sys:user:update']" class="item" effect="dark" content="修改当前用户信息" placement="top"
              :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showMessage(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-permission="['sys:user:delete']" class="item" effect="dark" content="删除当前用户" placement="top"
              :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteid(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-permission="['sys:user:repass']" class="item" effect="dark" content="修改当前用户密码" placement="top"
              :enterable="false">
              <el-button type="danger" icon="el-icon-key" size="mini" @click="showMessagePasswd(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip v-permission="['sys:user:update']" class="item" effect="dark" content="修改当前用户头像" placement="top"
              :enterable="false">
              <el-upload style="display: inline;margin-left:10px;" action="#" :show-file-list="false"
                :on-change="updateAvatar">
                <el-button type="danger" icon="el-icon-user" size="mini" @click="showUpdateAvatar(scope.row)">
                </el-button>
              </el-upload>

            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- 留言分页pc -->
      <div class="row ">
        <div class="block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" background :page-sizes="[4, 6, 8]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户信息" :visible.sync="centerDialogVisible" width="50%" center @close="addDialogClose">
      <!-- 表单内容区域 -->
      <el-form :model="addForm" status-icon :rules="addFromRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input type="text" clearable v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" clearable show-password v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input type="text" clearable v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" clearable v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item class="d-flex">
          <el-radio v-model="addForm.gender" label="男"> 男</el-radio>
          <el-radio v-model="addForm.gender" label="女"> 女</el-radio>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
        <el-button @click="addresetForm">重置</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息 -->
    <el-dialog title="修改用户信息" :visible.sync="centerDialogVisible2" width="50%" center>
      <!-- @close="editDialogClose" 有未知bug -->
      <!-- 表单内容区域 -->
      <el-form :model="editForm" status-icon :rules="addFromRules" ref="editFormRef" label-width="100px">
        <el-form-item hidden label="id" prop="id">
          <el-input type="hidden" v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input type="text" clearable v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input type="text" clearable v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" clearable v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="roles">
          <el-checkbox-group v-model="editForm.roles">
            <el-checkbox v-for="(item, index) in roles" :label="item.id" :key="index">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item class="d-flex">
          <el-radio v-model="editForm.gender" label="男"> 男</el-radio>
          <el-radio v-model="editForm.gender" label="女"> 女</el-radio>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
        <!-- <el-button @click="editResetForm">重置</el-button> -->
      </span>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog title="修改用户密码" :visible.sync="centerDialogVisible3" width="50%" center @close="editPasswordResetForm">

      <el-form :model="editFormPassword" status-icon :rules="addFromRules" ref="editFormPassword" label-width="100px">
        <el-form-item hidden label="id" prop="id">
          <el-input type="hidden" v-model="editFormPassword.id"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="password">
          <el-input type="password" clearable show-password v-model="editFormPassword.password" autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" show-password clearable v-model="editFormPassword.checkPass" autocomplete="off">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editPasswordResetFormClose">取 消</el-button>
        <el-button type="primary" @click="updataPassword">确 定</el-button>
        <el-button @click="editPasswordResetForm">重置</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from "qs";
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.editFormPassword.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 分页
      total: 0,
      pageSize: 5,
      currentPage: 1,
      searchContent: "", // 搜索内容
      userList: [],
      // 弹出框
      centerDialogVisible: false,
      centerDialogVisible2: false,
      centerDialogVisible3: false,
      dialogVisible: false,
      roles: [], // 角色选择
      avatarId: 1,
      //添加
      addForm: {
        username: "",
        password: "",
        phone: "",
        email: "",
        gender: "男",
      },
      //修改
      editForm: {
        id: 21,
        username: "",
        phone: "",
        email: "",
        roles: [],
        gender: "男",
      },
      editFormPassword: {
        id: 21,
        password: "",
        checkPass: "",
      },
      //验证规则
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        checkPass: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass2, trigger: "blur" },
        ],
        phone: [
          { message: "请输入手机号码", trigger: "blur" },
          { min: 11, max: 11, message: "长度在11位 ", trigger: "blur" },
        ],
        email: [
          { message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],
        role: [
          {
            required: true,
            message: "请输入从角色名称",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //删除列表

      multipleSelection: [], //批量删除列表
    };
  },
  created() {
    this.getUserList();
    this.getRoles();
  },
  methods: {
    // 获取所有用户
    async getUserList() {
      const data = await this.$http.get(
        "/admin/queryUser?" +
        qs.stringify({
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })
      );
      if (data.code == 200) {
        this.userList = data.data.records;
        this.total = data.data.total;
      }
      // console.log(this.userList);
    },
    // 分页
    handleSizeChange(pageSize) {
      this.currentPage = 1;
      this.pageSize = pageSize;
      this.getUserList();
    },
    // 跳转页数
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getUserList();
    },
    // 添加用户信息
    async add() {
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (valid) {
          const data = await this.$http.post("/admin/addUser", {
            username: this.addForm.username,
            password: this.addForm.password,
            phone: this.addForm.phone,
            email: this.addForm.email,
            gender: this.addForm.gender,
          });
          if (data.code == 200) {
            this.addresetForm();
            this.$message.success("添加成功！");
            this.getUserList();
          } else {
            this.$message.error("添加失败!");
          }
        } else {
          this.$message.error("表单填写有误，请检查后提交！");
        }
        this.centerDialogVisible = false;
      });
    },
    // 查询用户信息
    async search() {
      if (this.roles.includes(this.searchContent)) {
        const data = await this.$http.post(
          "/admin/queryUserByRoleName?" +
          qs.stringify({
            username: this.searchContent,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          })
        );
        if (data.code == 200) {
          this.userList = data.data.records;
          this.total = data.data.total;
          this.searchContent = "";
        } else {
          this.$message.error("查询用户不存在");
        }
      } else {
        const data = await this.$http.get(
          "/admin/queryUser?" +
          qs.stringify({
            username: this.searchContent,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          })
        );

        if (data.code == 200) {
          this.userList = data.data.records;
          this.total = data.data.total;
          this.searchContent = "";
        } else {
          this.$message.error("查询用户不存在");
        }
      }
    },
    // 获取角色列表
    async getRoles() {
      const data = await this.$http.post(
        "/admin/queryRole?" +
        qs.stringify({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
      );
      if (data.code == 200) {
        this.roles = data.data.records
      }
    },
    // 修改用户信息前获取点击用户的信息
    showMessage(row) {
      this.editForm.id = row.id;
      this.editForm.username = row.username;
      this.editForm.email = row.email;
      this.editForm.phone = row.phone;
      this.editForm.roles = []
      for (const item of row.roles) {
        this.editForm.roles.push(item["id"])
      }
      this.centerDialogVisible2 = true;
    },

    // 修改用户信息
    async edit() {
      this.$refs.editFormRef.validate(async (valid, obj) => {
        if (valid) {
          const data = await this.$http.post("/admin/updateUserModification", {
            sysUser: {
              id: this.editForm.id,
              phone: this.editForm.phone,
              email: this.editForm.email,
              gender: this.editForm.gender,
            },
            roleIds: this.editForm.roles,
          });
          if (data.code == 200) {
            this.$message.success("修改成功！");

            this.getUserList();
          }
        }
        this.centerDialogVisible2 = false;
      });
    },
    showMessagePasswd(row) {
      this.editFormPassword.id = row.id;
      this.centerDialogVisible3 = true;
    },
    // 修改密码
    async updataPassword() {
      this.$refs.editFormPassword.validate(async (valid, obj) => {
        if (valid) {
          const data = await this.$http.post("/admin/updateUserModificationPassword", {
            id: this.editFormPassword.id,
            password: this.editFormPassword.password,
          });
          if (data.code == 200) {
            this.$message.success("修改成功！");
            this.editPasswordResetFormClose();
            this.getUserList();
          } else if (data.code == 400) {
            this.$message.error(data.message);
          } else {
            this.$message.error("修改失败！");
          }
        }
      });
      this.centerDialogVisible3 = false;
    },
    updateAvatar(file) {
      this.uploadFile = file.raw
      if (this.uploadFile) {
        const form = new FormData()
        form.append('avatar', this.uploadFile, this.uploadFile.name)
        this.$http.request({
          url: '/users/modifyAvatar/' + this.avatarId,
          method: 'post',
          headers: { 'Content-Type': 'multipart/form-data' },
          data: form
        }
        ).then(res => {
          if (res.code === 200) {
            if (this.avatarId === this.$store.state.users.id) {
              const usersObj = JSON.parse(window.sessionStorage.getItem("usersObj"));
              const newAvatar = res.data.avatar
              window.sessionStorage.setItem("usersObj", JSON.stringify({ ...usersObj, ["avatar"]: newAvatar }));
              this.$store.commit("users", { ...usersObj, ["avatar"]: newAvatar })
            }
            this.getUserList()
          }
        })
      }
    },
    // 修改头像
    showUpdateAvatar(row) {
      this.avatarId = row.id
    },
    // 修改 关闭修改界面 清空所填信息
    editPasswordResetFormClose() {
      this.centerDialogVisible3 = false;
      this.$refs.editFormPassword.resetFields();
    },
    // 修改 取消修改信息 清空所填信息
    editPasswordResetForm() {
      this.$refs.editFormPassword.resetFields();
    },
    //添加 关闭添加界面 清空所填信息
    addresetForm() {
      this.$refs.addFormRef.resetFields();
    }, //添加 取添加改信息 清空所填信息
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 删出用户信息
    async deleteid(row) {
      const confirmresult = await this.$confirm(
        "此操作将永久删除该该用户,不可恢复， 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmresult != "confirm") {
        return this.$message.info("已取消删除！！");
      } else {
        const data = await this.$http.post("/admin/delUser/" + row.id);
        if (data.code == 200) {
          this.$message.success("成功删除了 " + row.username + "用户");
          this.getUserList();
        } else if (data.code == 400) {
          this.$message.error(data.message);
        } else {
          this.$message.error("删除失败");
        }
        this.centerDialogVisible2 = false;
      }
    },
    // 监听哪些行数改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除按钮
    async delAllSelection() {
      const length = this.multipleSelection.length;
      let delList = [];
      for (let i = 0; i < length; i++) {
        delList.push(this.multipleSelection[i].id);
      }
      const data = await this.$http.post("/admin/delAllUser", {
        list: delList,
      });
      if (data.code == 200) {
        let str = "";
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].username + "、";
        }
        this.$message.error(`成功删除了${str}` + "用户");
        this.getUserList();
      } else if (data.code == 400) {
        this.$message.error(data.message);
      } else {
        this.$message.error("删除失败");
      }
      this.multipleSelection = []; // 删除后清空列表
    },
    // 排序
    indexSort(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
  },
};
</script>

<style lang="less" scoped>
.table-td-headPortrait {
  width: 40px;
  height: 40px;
}
</style>
